package mo.offer_special;

import mo.common.ListNode;

import java.util.ArrayList;
import java.util.List;

public class L025 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //small
        List<Integer> value1 = new ArrayList<>();
        //large
        List<Integer> value2 = new ArrayList<>();
        while (l1 != null) {
            value1.add(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            value2.add(l2.val);
            l2 = l2.next;
        }
        if (value1.size() > value2.size()) {
            List<Integer> tmp = value1;
            value1 = value2;
            value2 = tmp;
        }
        int carry = 0;
        int min = value1.size()-1;
        int max = value2.size()-1;
        for (int i = 0; i <= min; i++) {
            int sum = value1.get(min-i) + value2.get(max-i) + carry;
            value2.set(max-i, sum % 10);
            carry = sum / 10;
        }
        if (carry != 0) {
            for (int i = min + 1; i <= max; i++) {
                int sum = value2.get(max-i) + carry;
                value2.set(max-i, sum % 10);
                carry = sum / 10;
                if (carry == 0) {
                    break;
                }
            }
        }
        if (carry == 1) {
            value2.add(0, carry);
        }

        ListNode res = new ListNode(value2.get(0));
        ListNode current = res;
        for (int i = 1; i <= max; i++) {
            current.next = new ListNode(value2.get(i));
            current = current.next;
        }
        return res;
    }

}
